<!--用户管理页-->
<template>
<div style="height:6vh;padding:10px 20px;background-color:#fff;display:flex;justify-content:space-between;align-items:center;">
  <span style="font-size:20px;font-weight:bold;">用户管理</span>
  <el-button type="primary" @click="beforeAddUser">新建用户</el-button>
</div>
  <!-- 新建用户弹窗 -->
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
  >
    <el-form
        label-width="100px"
        label-position="left"
        style="padding:0 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input v-model="addUserForm.username" :disabled="addUserForm.id!=null"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名">
            <el-input v-model="addUserForm.realName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 头像上传居中 -->
      <el-form-item label="头像" style="text-align:center;">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="addUserForm.avatar" :src="addUserForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="addUserForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别">
            <el-radio-group v-model="addUserForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="addUserForm.birthday"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width:100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="身份证号">
        <el-input v-model="addUserForm.idCard"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span style="flex:1"></span>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="addUser">保存</el-button>
    </template>
  </el-dialog>


  <!--    修改用户信息弹窗-->
  <el-dialog
      :title="updateDialogTitle"
      v-model="updateDialogVisible"
      width="600px"
      :before-close="handleUpdateClose"
  >
    <el-form
        label-width="100px"
        label-position="left"
        style="padding:0 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input v-model="EditUserForm.username" :disabled="EditUserForm.id!=null"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名">
            <el-input v-model="EditUserForm.realName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 头像上传居中 -->
      <el-form-item label="头像" style="text-align:center;">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="EditUserForm.avatar" :src="EditUserForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="EditUserForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="EditUserForm.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别">
            <el-radio-group v-model="EditUserForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="EditUserForm.birthday"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width:100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="身份证号">
        <el-input v-model="EditUserForm.idCard"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span style="flex:1"></span>
      <el-button @click="handleUpdateClose">取消</el-button>
      <el-button type="primary" @click="updateUser">保存</el-button>
    </template>
  </el-dialog>

  <!-- 用户搜索卡片 -->
<el-card style="margin:20px;border-radius:8px;">
<el-form :inline="true" style="display:flex;align-items:center;gap:15px;">
  <el-form-item label="用户搜索" style="margin-bottom:0;flex:1;">
    <el-input
        placeholder="输入真实姓名"
        v-model="searchUserForm.realName"
        style="width:100%"
    ></el-input>
  </el-form-item>
  <el-form-item style="margin-bottom:0;">
    <el-button @click="resetSearch">重置</el-button>
    <el-button type="primary" @click="loadUser">查询</el-button>
  </el-form-item>
</el-form>
</el-card>

  <!-- 用户列表卡片 用户表格数据-->
<el-card style="margin:20px;border-radius:8px;">
<el-table
    :data="userArr"
    stripe
    style="width:100%"
    header-row-class-name="table-header"
>
  <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
  <el-table-column label="用户名" prop="username" align="center"></el-table-column>
  <el-table-column label="真实姓名" prop="realName" align="center"></el-table-column>
  <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
  <el-table-column label="加入时间" prop="createTime" align="center"></el-table-column>
  <el-table-column label="操作" align="center" width="180">
    <template #default="scope">
      <el-button link type="primary" @click="editUser(scope.row.id)">编辑</el-button>
      <el-button
          link
          type="danger"
          :disabled="scope.row.level==40"
          @click="deleteUser(scope.row.id)"
      >删除</el-button>
    </template>
  </el-table-column>
</el-table>
</el-card>
  <!-- 页脚 -->
  <footer class="app-footer">
    <div class="container">
      <div class="footer-content">
        <p class="footer-title">安心陪诊后台管理系统</p>
        <p class="footer-links">
          &copy; 2025 安心陪诊平台 版权所有 |
          <a href="#" @click.prevent="goToUserAgreement">用户协议</a> |
          <a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a>
        </p>
      </div>
    </div>
  </footer>

</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";


//定义变量用来控制弹窗是否出现
const dialogVisible = ref(false);
// 控制更新用户信息弹窗
const updateDialogVisible = ref(false);
//  上传图片的url
const uploadUrl = `${BASE_URL}/v1/upload`;
// 上传处理方法
const handleAvatarSuccess = (response) => {
  if (response.state === 2000) {
    addUserForm.value.avatar = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};
// 上传处理方法(编辑)
const handleEditAvatarSuccess = (response) => {
  if (response.state === 2000) {
    EditEscortForm.value.avatar = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 上传头像前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过2MB!');
    return false;
  }
  return true;
};

//定义对象用来保存表单中的数据
const addUserForm = ref({
  username: '',
  realName: '',
  avatar: '',
  phone: '',
  email: '',
  gender: '',
  idCard: '',
  birthday: ''
})
//定义保存用户的方法
// 不再使用 qs.stringify，直接传对象
const addUser = () => {
  console.log('提交表单数据:', addUserForm.value);

  axios.post(`${BASE_URL}/v1/user/add`, addUserForm.value)
      .then(response => {
        if (response.data.state === 2000) {
          ElMessage.success('保存成功');
          dialogVisible.value = false;
          loadUser();
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
        ElMessage.error('请求失败，请检查网络或输入内容');
      });
}


//处理弹窗关闭方法
const handleClose = () => {
  ElMessageBox.confirm('确定要取消保存用户吗？所有未保存的更改将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    distinguishCancelAndClose: true
  }).then(() => {
    // 确认关闭后，关闭弹窗
    dialogVisible.value = false
    //清空表单
    addUserForm.value = {};
  }).catch(() => {
    // 用户点击了取消，不做任何操作
  })
}

const handleUpdateClose = () => {
  ElMessageBox.confirm('确定要取消编辑用户吗？所有未保存的更改将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    distinguishCancelAndClose: true
  }).then(() => {
    // 确认关闭后，关闭弹窗
    updateDialogVisible.value = false
    // 清空表单
    EditUserForm.value = {};
  }).catch(() => {
    // 用户点击了取消，不做任何操作
  })
}

//定义对象来保存用户查询的条件
const searchUserForm = ref({username: ''});
//定义对象保存查询到的用户表格数据
const userArr = ref([]);
//定义加载用户列表的方法
const loadUser = () => {
  let data = qs.stringify(searchUserForm.value);
  console.log(data);
  //如果有查询条件,就根据条件查,没有条件默认查全部数据
  axios.get(BASE_URL + '/v1/user/select?' + data)
      .then((response) => {//回调函数,处理响应数据
        if (response.data.state == 2000) {
          //后端返回的状态码是2000说明成功了
          userArr.value = response.data.data;//把请求回来的数据装到绑定表格的数组中
          console.log(userArr.value);
        } else {
          ElMessage.error(response.data.msg + "出错了");
        }
      })
}

//页面一加载完毕,立即执行
onMounted(() => {
  loadUser();
})

//重置搜索
const resetSearch = () => {
  //清空之前的搜索内容
  searchUserForm.value = {};
  //重新加载所有的用户数据
  loadUser();
}

//定义变量用来保存弹窗的标题
const dialogTitle = ref('新建用户');
const updateDialogTitle = ref('编辑用户');
//定义点击新增用户按钮时调用的方法:处理新增用户时弹窗的标题
const beforeAddUser = () => {
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
}

const EditUserForm = ref({});
//定义编辑用户的方法
const editUser = (id) => {
  updateDialogTitle.value = '编辑用户';
  updateDialogVisible.value = true;
  //获取当前待编辑的用户数据,回显在弹窗中
  axios.get(BASE_URL + `/v1/user/${id}`).then((response) => {
    if (response.data.state == 2000) {
      console.log('*************')
      console.log(response)
      //后端返回的是单个UserVO对象
      EditUserForm.value = response.data.data;
      console.log(EditUserForm)
    } else {
      ElMessage.error(response.data.msg + "出错了");
    }
  })
}

// 更新用户信息 - 修改为直接发送JSON
const updateUser = () => {
  axios.post(BASE_URL + `/v1/user/update`, EditUserForm.value, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((response) => {
    if (response.data.state == 2000) {
      ElMessage.success('更新成功')
      EditUserForm.value = {};
      updateDialogVisible.value = false;
      loadUser();
    } else {
      ElMessage.error(response.data.msg + "出错了");
    }
  })
}

//创建删除员工的方法
// 删除用户 - 修改为路径参数方式
const deleteUser = (Id) => {
  ElMessageBox.confirm('您确认要删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post(`${BASE_URL}/v1/user/delete/${Id}`).then((response) => {
      if (response.data.state === 2000) {
        ElMessage.success('删除成功!');
        loadUser();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
  })
}

</script>

<style scoped>
.center-row {
  display: flex;
  justify-content: center;
}

.avatar-uploader {
  display: flex;
  justify-content: flex-start; /* 从左侧开始排列 */
  padding-left: 20px; /* 添加内边距 */
  width: 100%;
  box-sizing: border-box; /* 确保padding不影响总宽度 */
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

/* 页脚样式 */
.app-footer {
  background-color: #f5f7fa;
  padding: 25px 0;
  border-top: 1px solid #e6e6e6;
  margin-top: 40px;
}

.footer-content {
  text-align: center;
}

.footer-title {
  color: #606266;
  margin-bottom: 12px;
  font-size: 15px;
}

.footer-links {
  color: #909399;
  font-size: 13px;
}

.footer-links a {
  color: #909399;
  transition: color 0.3s;
  margin: 0 5px;
}

.footer-links a:hover {
  color: #a6d2ff;
}
</style>